<template>
  <div class="suvey">
    <div class="surveyName" v-if="currentStep === 1">
      <h2>{{ survey.name }}</h2>
    </div>

    <!--开场白部分-->
    <div class="startShow" v-if="currentStep === 1">
      <h1>开场欢迎： {{ textFilter(survey.startShow ? survey.startShow : loadingText) }}</h1>
    </div>
    <!--问卷调查部分-->
    <div class="collect-area" v-if="currentStep === 2">
      <el-row :gutter="20">
        <el-col :span="18" :offset="3">
          <div class="process-area">
            <el-row>
              <el-col :span="24">
                <el-row>
                  <el-col :span="18">
                    <el-progress class="progress" :text-inside="true" :stroke-width="20"
                                 :percentage="this.questions.length ? (this.currentOrderNum / this.questions.length).toFixed(3) * 100 : 0"
                                 status="success"></el-progress>
                  </el-col>
                  <el-col :span="6">
                    <span class="question-process">当前第 {{ currentOrderNum }} 题/共 {{ questions.length }} 题</span>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </div>
          <div class="box-card-head" v-if="questions.length">
            <div>
              <el-button size="mini" type="danger" icon="el-icon-location-information" circle></el-button>
              [{{
                getQuestion(currentOrderNum) && getQuestion(currentOrderNum).type.value === 1 ? '单选题' : '多选题'
              }}]
            </div>
          </div>
          <el-card class="box-card" v-for="(item, index) in questions" :key="index"
                   v-if="currentOrderNum === item.orderNum">
            <template>
              <div class="text item qustion-name">
                <span style="font-weight: bold">第{{ item.orderNum }}题.</span> {{ textFilter(item.name) }}
              </div>
              <!-- 单选题-->
              <el-radio-group v-model="item.answers" style="width: 100%"
                              v-if="item.type && item.type.value === 1">
                <el-radio :label="opt" v-for="(opt, i) in item.children" :key="i">{{ opt.orderNum }}.
                  {{ textFilter(opt.name) }}

                  <span v-if="opt.remark">({{ opt.remark }})</span>
                  <el-button size="mini" @click="editRemark(opt)" v-if="opt.hasRemark === 1">修改备注</el-button>
                </el-radio>
              </el-radio-group>
              <!--多选题-->
              <el-checkbox-group v-model="item.answers"
                                 v-if="item.type && item.type.value === 2">

                <el-checkbox :label="opt" v-for="opt in item.children" :key="opt.id">{{ opt.orderNum }}.
                  {{ textFilter(opt.name) }}

                </el-checkbox>
              </el-checkbox-group>
            </template>

            <div>
            </div>
            <div style="margin-top: 10px">
              <el-button v-if="currentStep === 2" type="mini" icon="el-icon-arrow-left" @click="preQuestion(item)">上一题
              </el-button>
              <el-button v-if="currentStep === 2" type="mini" @click="nextQuestion(item)">下一题
                <i class="el-icon-arrow-right el-icon--right"></i></el-button>
            </div>
          </el-card>
          <el-card class="box-card-footer" style="text-align: left;">
            <div class="answer-card" style="text-align: left; font-size: 14px; display: inline-block;">
              <span>答题卡
                <i @click="showCard = !showCard" class="el-icon-arrow-down" style="font-weight: bold"
                   v-if="!showCard"></i>
                <i @click="showCard = !showCard" class="el-icon-arrow-up" style="font-weight: bold" v-if="showCard"></i></span>
              <el-collapse-transition>
                <div v-show="showCard">
                  <ul class="list-unstyled">
                    <li v-for="item in questions"
                        :class="{'answer-card-answered' : answerCardSaved(item), 'answer-card-active': answerCardActive(item)}">
                      {{ item.orderNum }}
                    </li>
                  </ul>
                </div>
              </el-collapse-transition>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>
    <!--结束语部分-->
    <div class="endShow" v-if="currentStep === 3">
      <h1>结束感谢： {{ textFilter(survey.endShow ? survey.endShow : loadingText) }}</h1>
    </div>
    <!--操作按钮部分-->
    <div class="opt-area">
      <el-button v-if="currentStep === 1" @click="changeStep(1)">开始</el-button>
      <div v-if="currentStep === 3">
        <el-button class="el-button--danger" @click="toCancel()">
          作废
        </el-button>
        <el-button class="el-button--success" @click="doPass()">
          通过
        </el-button>
      </div>

      <div v-if="currentStep === 4">
          <span>操作完成</span>
      </div>
    </div>

    <el-dialog
      title="提示"
      :visible.sync="dialogVisible"
      width="30%">
      <el-input v-model="selectOption.remark" placeholder="请输入备注内容"></el-input>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogVisible = false">确 定</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>
import {
  answerDetail,
  answerOptionDetail,
  checkCancel,
  checkPass,
  submitAnswers,
  surveyDesign,
  surveydetail
} from "../api/baseMG";

export default {
  name: 'Check',
  props: {
    active: Boolean,
    surveyId: Number,
    phone: String,
    agentId: String,
    seat: String,
    answerId: Number,
    updateMode: Boolean
  },
  data() {
    return {
      selectOption: {},
      dialogVisible: false,
      historys: [],
      jumpPool: [],
      answers: [],
      currentOrderNum: 1,
      showCard: false,
      loadingText: "正在加载中...",
      survey: {},
      questions: [],
      currentStep: 1, // 当前操作步骤： 1   开场白部分 2 调查部分 3 结束部分
      cusInfo: {}     // 查询到的到的信息
    }
  },
  filters: {},
  created() {
    // 没数据就关掉
    this.initPage();
  },
  watch: {
    answerId(n, o) {
      this.initPage();
    },
    active(n, o) {
      if (n) {
        this.loadSurvey();
        this.loadCusInfo();
        this.survey = {};
        this.questions = [];
        this.currentStep = 1;
        this.loadCusInfo();
        this.counter = {
          flag: null,
          one: '00', // 时
          two: '00', // 分
          three: '00', // 秒
          abc: 0, // 秒的计数
          cde: 0, // 分的计数
          efg: 0 // 时的计数
        };
        this.startHandler();
      } else {
        this.survey = {};
        this.questions = [];
        this.currentStep = 1;
        this.loadCusInfo();
        if (this.counter.flag) {
          clearInterval(this.counter.flag);
        }
        this.counter = {
          flag: null,
          one: '00', // 时
          two: '00', // 分
          three: '00', // 秒
          abc: 0, // 秒的计数
          cde: 0, // 分的计数
          efg: 0 // 时的计数
        };
      }
    }
  },
  methods: {
    doPass() {
      // 审核作废
      checkPass(this.answerId, 100).then(resp => {
        this.$message({
          type: resp.success ? 'success' : 'error',
          message: resp.msg
        });
        this.initPage();
        this.$emit("checkBack", true)
      }).catch(e => {

      })
    },
    // 准备作废
    toCancel() {
      this.$prompt('请输入作废原因', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
      }).then(({ value }) => {
        this.doCancel(value)
      }).catch(() => {
      });
    },
    doCancel(reviewMsg) {
      // 通过审核
      checkCancel(this.answerId, reviewMsg, 100).then(resp => {
          this.$message({
            type: resp.success ? 'success' : 'error',
            message: resp.msg
          });
          this.initPage();
          this.$emit("checkBack", false)
      }).catch(e => {

      })
    },
    loadAnswer() {
      if (!this.answerId) {
        return;
      }
      answerOptionDetail(this.answerId).then(resp => {
        if (resp.success) {
          // 答题数据
          for (let i = 0; i < resp.data.length; i++) {
            let answer = resp.data[i];
            // 题目信息
            for (let j = 0; j < this.questions.length; j++) {
              let question = this.questions[j];
              for (let k = 0; k < question.children.length; k++) {
                let child = question.children[k];
                if (question.id === answer.questionId && child.id === answer.optionId) {
                  if (question.type.value === 1) {
                    question.answers = child;
                  } else {
                    question.answers.push(child);
                  }
                }
              }
            }
          }
        }

      })
    },
    initPage() {
      if (!this.surveyId) {
        this.survey = {};
        this.questions = [];
        this.currentStep = 1;
        this.cusInfo = {};
        this.$emit("statusChange", {active: false});
      } else {
        this.$forceUpdate();
        this.currentOrderNum = 1;
        this.currentStep = 1;
        this.questions = [];
        this.historys = [];
        this.selectOption = {};
        this.loadSurvey();
        this.loadCusInfo();
        this.historys = [];
        this.jumpPool = [];
        // this.startHandler();
      }
    },
    editRemark(opt) {
      this.selectOption = opt;
      this.dialogVisible = true;
    },
    chooseItem(e) {
      if (e.currentTarget.tagName === 'DIV') {
        e.currentTarget.firstElementChild.click();
      }
    },
    answerCardSaved(item) {
      return this.historys.indexOf(item.orderNum) > -1;
    },
    answerCardActive(item) {
      return this.currentOrderNum === item.orderNum;
    },
    nextQuestion(question) {
      // 获取答案
      let answers = question.answers;
      if (answers instanceof Array) {
        // 如果选项中有结束的直接结束
        if (!answers.length) {
          this.$message({
            type: 'warning',
            message: '问卷不允许不作答'
          });
          return;
        }
        for (let i = 0; i < answers.length; i++) {
          let answer = answers[i];
          if (!answer.target) {
            // 直接进入结束步骤
            this.jumpPool.push(answer.target);
            this.currentStep = 3;
            // 保存
          } else {
            this.jumpPool.push(answer.target);
          }
        }
      } else {
        if (!answers.id) {
          this.$message({
            type: 'warning',
            message: '问卷不允许不作答'
          });
          return;
        }
        if (!answers.target) {
          // 直接进入结束步骤
          this.currentStep = 3;
          // 保存
        }
        this.jumpPool.push(answers.target)
      }

      this.historys.push(this.currentOrderNum);
      this.answers.push(question);
      if (this.jumpPool.length > 0) {
        this.currentOrderNum = this.jumpPool.shift();
        return;
      }
      this.$message({
        type: 'error',
        message: '未知异常'
      });
    },
    preQuestion() {
      if (this.historys.length > 0) {
        this.currentOrderNum = this.historys.pop();
        this.answers.pop();
      } else {
        this.$message({
          type: 'warning',
          message: '没有了'
        });
      }

    },
    // 根据序号获取问题
    getQuestion(orderNum) {
      for (let i = 0; i < this.questions.length; i++) {
        let question = this.questions[i];
        if (question.orderNum === orderNum) {
          return question;
        }
      }
    },
    // 获取号码信息
    loadCusInfo() {
      this.cusInfo = {'地区': "杭州市", "政策": "五水共治-河道清理", "活动名称": "五水共治", "类型": "社会监督"}
    },
    textFilter(text) {
      if (!this.cusInfo) {
        return text;
      }
      for (let p in this.cusInfo) {
        let tem = "#{" + p + "}";
        let v = this.cusInfo[p];
        if (!v) {
          continue;
        }
        if (text.indexOf(tem) > -1) {
          text = text.replace(tem, v);
        }
      }
      return text;
    },
    changeStep(step) {
      if (step === 1) {
        this.currentStep++;
      } else if (step === 2) {
        this.currentStep++;
      } else if (step === 3) {
        this.currentStep++;
        submitAnswers(this.answers, this.agentId, this.phone, this.surveyId).then(resp => {
          if (resp.success) {
            this.$message.success(resp.msg);
          } else {
            this.$message.error(resp.msg);
          }
        }).catch(e => {

        })
      } else {
        // 关闭窗口
        hangUp();
        this.$emit("statusChange", {active: false});
      }
    },
    loadSurvey() {
      surveydetail(this.surveyId).then(resp => {
        this.survey = resp.data;
      });

      surveyDesign({id: this.surveyId}).then(resp => {
        this.questions = resp.data.sort((a, b) => a.orderNum - b.orderNum);
        if (!this.questions.length) {
          this.$message.error("无效的问卷,缺少题目,请联系管理员");
        }
        if (this.updateMode) {
          this.loadAnswer();
        }
      })
    },
    startHandler() {
      if (this.counter.flag) {
        return;
      }
      this.counter.flag = setInterval(() => {
        if (this.counter.three === 60 || this.counter.three === '60') {
          this.counter.three = '00';
          this.counter.abc = 0;
          if (this.counter.two === 60 || this.counter.two === '60') {
            this.counter.two = '00';
            this.counter.counter.cde = 0;
            if (this.counter.efg + 1 <= 9) {
              this.counter.efg++;
              this.counter.one = '0' + this.counter.efg;
            } else {
              this.counter.efg++;
              this.counter.one = this.counter.efg;
            }
          } else {
            if (this.counter.cde + 1 <= 9) {
              this.counter.cde++;
              this.counter.two = '0' + this.counter.cde;
            } else {
              this.counter.cde++;
              this.counter.two = this.counter.cde;
            }
          }
        } else {
          if (this.counter.abc + 1 <= 9) {
            this.counter.abc++;
            this.counter.three = '0' + this.counter.abc;
          } else {
            this.counter.abc++;
            this.counter.three = this.counter.abc;
          }
        }

      }, 1000)
    }

  }
}
</script>

<style scoped>
.suvey {
  //height: 700px;
}

.surveyName {
  text-align: center;
}

.startShow {
  text-align: center;
}

.endShow {
  text-align: center;
}

.opt-area {
  text-align: center;
  margin-top: 30px;
}

.collect-area {
  text-align: center;
}

.item {
  /*border-top: 1px solid #6f7180;*/
}

.qustion-name {
  text-align: left;
  font-size: 14px;
}

.el-radio {
  text-align: left;
  font-size: 14px;
  padding: 10px;
  word-break: break-all;
  width: 100%;
  margin-top: 10px;
  border: 1px solid #c0c4cc;
}

.el-checkbox {
  text-align: left;
  font-size: 14px;
  padding: 15px;
  word-break: break-all;
  margin-top: 10px;
  width: 100%;
  border: 1px solid #c0c4cc;
}

.option-name:hover {
  background-color: whitesmoke;
}

.process-area {
  background-color: #2c3e50;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  min-height: 40px;
  border-radius: 5px 5px 0 0;
  color: #ffffff;
}

.progress {
  line-height: 40px;
  padding: 0 20px;
}

.question-process {
  line-height: 40px;
  text-align: center;
}

.box-card {
  border-left: 1px solid #c0c4cc;
  border-right: 1px solid #c0c4cc;
  border-bottom: 1px dashed #c0c4cc;
  border-radius: 0px;
}

.box-card-footer {
  border-left: 1px solid #c0c4cc;
  border-right: 1px solid #c0c4cc;
  border-bottom: 1px solid #c0c4cc;
  border-radius: 0px 0px 3px 3px;
}

.box-card-head {
  border-left: 1px solid #c0c4cc;
  border-right: 1px solid #c0c4cc;
  border-bottom: 1px dashed #c0c4cc;
  border-radius: 0px 0px 3px 3px;
  text-align: left;
  padding: 5px;
  font-size: 14px;
}

.list-unstyled {
  padding-left: 0;
  list-style: none;
}

.list-unstyled li {
  display: inline-block;
  width: 35px;
  height: 35px;
  border: 1px solid #90909052;
  color: #00BC9B;
  margin: 5px;
  line-height: 35px;
  text-align: center;
}

.answer-card {
  width: 100%;
}

.answer-card-active {
  background-color: #5daf34;
  color: white !important;
}

.answer-card-answered {
  background-color: #bbbbbb;
}

</style>
